<!-- 监管对象管理 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="numberPlate">
        <el-input v-model="queryParams.numberPlate" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所属公司" prop="companyId">
        <el-tree-select v-model="queryParams.companyId" placeholder="请选择所属公司" clearable :data="treeList"
          :expand-on-click-node="false" :render-after-expand="false" @change="handleQuery" check-strictly
          :props="{ label: 'label' }" node-key="id" filterable />
      </el-form-item>
      <el-form-item label="绑定状态" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" clearable filterable :placeholder="'请输入绑定状态'" @change="handleQuery">
          <el-option v-for="item in sel_option.bindStatus" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select> </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['comlbs:vehicleManagement:add']">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comlbs:vehicleManagement:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['comlbs:vehicleManagement:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table highlight-current-row v-loading="loading" :data="vehicleManagementList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="监管对象图标" align="left" prop="objIcon">
        <template #default="scope">
          <img :src="myRequire('equipment/' + scope.row.objIcon + '.png')" />
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="left" prop="numberPlate" />
      <el-table-column label="所属公司" align="left" prop="companyName" />
      <el-table-column label="上级公司" align="left" prop="parentCompanyName" />
      <el-table-column label="图片" align="left" prop="vehiclePic">
        <template #default="scope">
          <img v-if="scope.row.vehiclePic && scope.row.vehiclePic.length > 0" :src="getImgSrc(scope.row.vehiclePic[0])"
            width="44" height="44" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="left" prop="createTime" width="180" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleDetail(scope.row)"
            v-hasPermi="['comlbs:vehicleManagement:detail']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['comlbs:vehicleManagement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-if="!scope.row.bindStatus"
            v-hasPermi="['comlbs:vehicleManagement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body destroy-on-close>
      <el-form ref="vehicleManagementRef" :model="form" :rules="rules" label-width="120px" :inline="true"
        :disabled="disabled">
        <el-form-item v-for="v in supervisionItem[supervisionArr[Number(form.objType)]]" :key="v.prop" :label="v.name"
          :prop="v.prop" :style="{ width: v.type != 'photo' ? 'calc(50% - 32px)' : '' }">
          <div v-if="v.prop == 'objIcon'" class="icon-div">
            <img v-for="(item, i) in supervisionImg[supervisionArr[Number(form.objType)]]" :key="i"
              :src="myRequire('equipment/' + item + '.png')" @click="changeImg(i)">
          </div>
          <el-select v-else-if="v.type == 'select'" v-model="form[v.prop]" filterable clearable>
            <el-option v-for="item in sel_option[v.prop]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-input v-else-if="v.type == 'input'" v-model.trim="form[v.prop]" clearable
            @blur="onFormItemBlur(v.prop)"></el-input>
          <el-tree-select v-else-if="v.type == 'treeSelect'" v-model="form[v.prop]" clearable :data="sel_option[v.prop]"
            :expand-on-click-node="false" :render-after-expand="false" check-strictly :props="{ label: 'label' }"
            node-key="id" filterable placeholder=" " style="width:228px" />
          <div v-else-if="v.type == 'photo'" style="width:500px;height: 156px;">
            <ImageUpload ref="myUploadPic" url='/system/dept/uploadFile' :pictures='form.vehiclePic || []'
              :disabled="disabled">
            </ImageUpload>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VehicleManagement">
import dayjs from "dayjs"
import request from '@/utils/request'
import { listDeviceManagement, delDeviceManagement, addDeviceManagement, updateDeviceManagement } from "@/api/comlbs/vehicleManagement";
import { treeDept } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
const vehicleManagementList = ref([]);
const open = ref(false);
const disabled = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const blurFlags = ref({}) // 用于记录各表单项是否已执行过验证
function myRequire(str) {
  return new URL(`../../../assets/img/${str}`, import.meta.url).href
}
let validateBool = false;
// 设备名称重复验证
let numberPlateValidate = async (rule, value, callback) => {
  validateBool = false;
  if (value === '' || !value) {
    callback(new Error('不能为空'));
  } else {
    if (!form.value.companyId) return
    let url = "/comlbs/vehicleManagement/checkExistNumberPlate", _data;
    _data = {
      objId: form.value.id,
      numberPlate: form.value.numberPlate,
      companyId: form.value.companyId,
      objType: form.value.objType
    }
    const data = await request({
      url: url,
      method: 'post',
      data: _data,
    })
    if (data.code == 200) {
      validateBool = true;
      callback();
    } else {
      callback(new Error('该名称已存在'))
    }
  }
}
// 设备图标，此处验证设置为通过，在提交表单时验证是否为空
let objIconValidate = async (rule, value, callback) => {
  if (value == '' || !value) {
    callback()
    return
  }
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 15,
    companyId: null,
    numberPlate: null
  },
  rules: {
    numberPlate: [
      { required: true, validator: numberPlateValidate, trigger: 'blur' },
    ],
    objIcon: [
      { required: true, validator: objIconValidate, trigger: 'blur' },
    ],
    companyId: [
      { required: true, type: "string", message: '请选择所属公司', trigger: 'input' }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
const { bindStatus } = proxy.useDict("bindStatus");
const sel_option = ref({ bindStatus })
proxy.setDataByDictType(sel_option.value, 'sys_user_sex', 'ownerSex');
const treeList = ref([]);
treeDept().then(res => {
  treeList.value = res.data
  sel_option.value.companyId = res.data
});

function getImgSrc(val) {
  if (val && val.path) {
    return import.meta.env.VITE_APP_BASE_API + val.path;
  }
  else return "";
}

function onFormItemBlur(prop) {
  // 标记该表单项已经执行过验证
  blurFlags.value[prop] = true;
}

/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  listDeviceManagement(queryParams.value).then(response => {
    vehicleManagementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  setTimeout(() => {
    reset();
  }, 200)
}

// 监管类型 
const supervisionItem = ref({
  car: [
    { name: '车辆图标', prop: 'objIcon', type: 'img' },
    { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
    { name: '车辆名称', prop: 'numberPlate', type: 'input' },
    { name: '车辆型号', prop: 'vehicleModel', type: 'input' },
    { name: '颜色', prop: 'vehicleColor', type: 'input' },
    { name: '车辆图片', prop: 'vehiclePic', type: 'photo' },
  ],
  ship: [
    { name: '船舶图标', prop: 'objIcon', type: 'img' },
    { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
    { name: '船牌号', prop: 'numberPlate', type: 'input' },
    { name: '船舶型号', prop: 'vehicleModel', type: 'input' },
    { name: '颜色', prop: 'vehicleColor', type: 'input' },
    { name: '船舶图片', prop: 'picture', type: 'photo' },
  ],
  person: [
    { name: '人员图标', prop: 'objIcon', type: 'img' },
    { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
    { name: '人员姓名', prop: 'numberPlate', type: 'input' },
    { name: '性别', prop: 'ownerSex', type: 'select' },
    { name: '联系方式', prop: 'contactNumber', type: 'input' },
    { name: '年龄', prop: 'age', type: 'input' },
    { name: '人员图片', prop: 'vehiclePic', type: 'photo' },
  ],
  goods: [
    { name: '物品图标', prop: 'objIcon', type: 'img' },
    { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
    { name: '物品名称', prop: 'numberPlate', type: 'input' },
    { name: '物品图片', prop: 'vehiclePic', type: 'photo' },
  ],
  animal: [
    { name: '动物图标', prop: 'objIcon', type: 'img' },
    { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
    { name: '动物名称', prop: 'numberPlate', type: 'input' },
    { name: '动物图片', prop: 'vehiclePic', type: 'photo' },
  ],
  other: [
    { name: '其他图标', prop: 'objIcon', type: 'img' },
    { name: '所属公司', prop: 'companyId', type: 'treeSelect' },
    { name: '设备名称', prop: 'numberPlate', type: 'input' },
    { name: '图片附件', prop: 'vehiclePic', type: 'photo' },
  ],
})
// 储存监管类型共用大类名字
const supervisionArr = ref(GlobalSetting.equipArr)
const supervisionImg = ref(GlobalSetting.equipImg)
const activeImgIndex = ref(null);
// 表单重置
function reset() {
  form.value = {
    id: null,
    companyId: null,
    deviceName: null,
    deviceColor: null,
    devicePic: null,
    numberPlate: null,
    plateColor: null,
    bindId: null,
    bindStatus: null,
    serviceStartTime: null,
    operateType: null,
    cityCode: null,
    deviceType: null,
    deviceBrand: null,
    deviceModel: null,
    businessLine: null,
    equipmentInstallTime: null,
    ownerName: null,
    contactNumber: null,
    ownerSex: null,
    idCard: null,
    failureTime: null,
    gmtCreate: null,
    gmtModified: null,
    createUserId: null,
    modifiedUserId: null,
    objIcon: null,
    objType: null,
    age: null
  };
  proxy.resetForm("vehicleManagementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 设备图标恢复初始状态
function resetSupervisionImg() {
  // 设备图标恢复初始状态
  activeImgIndex.value = null // 讲当前选中图片index置null
  for (let i = 0; i < 5; i++) {
    let svsTypeImg = supervisionArr.value[i]// 监管类型的设备图标数组名
    for (let j = 0; j < supervisionImg.value[svsTypeImg].length; j++) {
      if (supervisionImg.value[svsTypeImg][j].indexOf('_active') > -1)
        // 移除str中的_active
        supervisionImg.value[svsTypeImg][j] = supervisionImg.value[svsTypeImg][j].slice(0, supervisionImg.value[svsTypeImg][j].length - 7);
    }
  }
}
// 新增编辑框-设备图标选中切换逻辑
function changeImg(index) {
  if (disabled.value) return
  if (activeImgIndex.value == index) return
  activeImgIndex.value = index;

  let arr = supervisionImg.value[supervisionArr.value[Number(form.value.objType)]]
  arr[index] += '_active'
  arr.forEach((v, i) => {
    if (i != index && v.indexOf('_active') > -1) {
      arr[i] = v.slice(0, v.length - 7)
    }
  })
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  disabled.value = false;
  open.value = true;
  title.value = "添加对象";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  disabled.value = false;
  form.value = JSON.parse(JSON.stringify(row));
  form.value.ownerSex = row.ownerSex == null ? row.ownerSex : row.ownerSex + '';
  blurFlags.value = {};
  resetSupervisionImg();
  // 监管类型不为空时
  if (row.objType || row.objType === 0) {
    // 设备图标回显处理   监管类型supervisionType（数据字典：0设备 1船舶 2人员 3物品 4动物）
    let svsTypeArr = supervisionImg.value[supervisionArr.value[row.objType]] // 当前监管类型的设备图标数组
    svsTypeArr.forEach((v, i) => {
      if (row.objIcon.indexOf(v) > -1) supervisionImg.value[supervisionArr.value[row.objType]][i] = row.objIcon + '_active'
    })
  }
  open.value = true;
  title.value = "修改对象";
}

/** 详情按钮操作 */
function handleDetail(row) {
  handleUpdate(row);
  disabled.value = true;
  title.value = "对象详情";
}

/** 提交按钮 */
async function submitForm() {
  let _data = {
    vehicleColor: form.value.vehicleColor,
    companyId: form.value.companyId,
    ownerSex: form.value.ownerSex,
    idCard: form.value.idCard,
    contactNumber: form.value.contactNumber,
    vehicleModel: form.value.vehicleModel,
    id: form.value.id,
    numberPlate: form.value.numberPlate,
    age: form.value.age,
  }
  let imgArr = supervisionImg.value[supervisionArr.value[form.value.objType]]
  if (imgArr && imgArr.length > 0) {
    imgArr.forEach(v => {
      if (v.indexOf('_active') > -1) _data.objIcon = v.split('_')[0]
    })
  }
  _data.vehiclePic = await proxy.$refs["myUploadPic"]?.[0]?.uploadInfo();
  const fieldKeys = Object.keys(rules.value);
  const fieldsToValidate = fieldKeys.filter(key => !blurFlags.value[key]);
  proxy.$refs["vehicleManagementRef"].validateField(fieldsToValidate, valid => {
    if (valid && validateBool) {
      if (form.value.id != null) {
        updateDeviceManagement(_data).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDeviceManagement(_data).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const length = row.id ? 1 : ids.value.length;
  proxy.$modal.confirm('是否确认删除这' + length + '项数据？').then(function () {
    return delDeviceManagement(row.id ?? ids.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comlbs/vehicleManagement/export', {
    ...queryParams.value
  }, `监管对象管理_${dayjs(new Date()).format("YYYY-MM-DD_HH:mm:ss")}.xlsx`)
}

getList();
</script>
